package com.ncucoder.jwva.util;

import org.apache.commons.lang3.StringUtils;

/**
 * @author <a href="https://edit.ncucoder.com">hsowan</a>
 * @since 2019-01-01 23:04
 */
public class IpUtil {
    public static long ipToLong(String ipAddress) {
        long result = 0;
        String[] ipAddressInArray = StringUtils.split(ipAddress, ".");
        for (int i = 3; i >= 0; i--) {
            long ip = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ip << (i * 8);
        }
        return result;
    }

    public static String longToIp(long ip) {
        StringBuilder sb = new StringBuilder(15);
        for (int i = 0; i < 4; i++) {
            sb.insert(0, Long.toString(ip & 0xff));
            if (i < 3) {
                sb.insert(0, '.');
            }
            ip = ip >> 8;
        }
        return sb.toString();
    }
}
